// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../divider/kq_divider.dart';

/// 通用展开收起控件
///
/// @author 周卓
///
// ignore: must_be_immutable
class KqExpandGroup extends StatefulWidget {
  /// 是否展开
  late bool expanded;

  /// 展开折叠回调
  final ValueChanged<bool>? onExpansionChanged;

  /// 分组的布局
  final Widget headerWidget;

  /// 子控件
  final List<Widget> childWidgets;

  /// 头部背景颜色
  final Color? backgroundColor;

  /// 头部的左边内边距，注意，默认有个16内边距，这个是额外的边距
  final double headerExtraPaddingLeft;

  /// 头部分割线颜色
  final Color? dividerColor;

  /// 子控件的左边统一内边距，默认为0
  final double childPaddingLeft;

  /// 头部水平边距
  final double? headerPaddingHorizontal;

  /// 头部垂直边距
  final double? headerPaddingVertical;

  /// 隐藏底部分割线
  final bool hideDivider;

  /// 收起时的箭头图标路径
  final String? iconDownArrow;

  /// 折叠时的箭头图标路径
  final String? iconUpArrow;

  /// 箭头和头部的间距，默认为0
  final double arrowHeaderSpacing;

  /// 箭头的位置，左侧还是右侧
  final ArrowPosition arrowPosition;

  /// 箭头的颜色
  final Color? arrowIconColor;

  KqExpandGroup({
    Key? key,
    required this.headerWidget,
    required this.childWidgets,
    this.onExpansionChanged,
    this.headerPaddingHorizontal,
    this.headerPaddingVertical,
    this.backgroundColor,
    this.dividerColor,
    this.headerExtraPaddingLeft = 0,
    this.childPaddingLeft = 0,
    this.arrowHeaderSpacing = 0,
    this.arrowPosition = ArrowPosition.right,
    this.iconDownArrow,
    this.iconUpArrow,
    this.arrowIconColor,
    this.hideDivider = false,
    this.expanded = false,
  }) : super(key: key);

  @override
  State<KqExpandGroup> createState() =>
      _KqExpandGroupWithEntityState();
}

class _KqExpandGroupWithEntityState extends State<KqExpandGroup>
    with SingleTickerProviderStateMixin {
  static final Animatable<double> _easeInTween =
      CurveTween(curve: Curves.easeIn);

  late AnimationController _controller;
  late Animation<double> _heightFactor;

  bool _isExpanded = false;
  Widget? arrowIconLeftDown;
  Widget? arrowIconLeftUp;
  Widget? arrowIconRight;

  @override
  void initState() {
    super.initState();
    _isExpanded =
        PageStorage.of(context).readState(context) ?? widget.expanded;

    _controller = AnimationController(
        duration: const Duration(milliseconds: 150) /*_kExpand*/, vsync: this);
    _heightFactor = _controller.drive(_easeInTween);

    if (_isExpanded) {
      _controller.value = 1.0;
    }
  }

  @override
  void didUpdateWidget(covariant KqExpandGroup oldWidget) {
    if (widget.expanded != _isExpanded) {
      _isExpanded = widget.expanded;
      if (_isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse().then<void>((void value) {
          if (!mounted) return;
        });
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _handleTap() {
    setState(() {
      _isExpanded = !_isExpanded;
      widget.expanded = _isExpanded;
      if (_isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse().then<void>((void value) {
          if (!mounted) return;
        });
      }
      PageStorage.of(context).writeState(context, _isExpanded);
    });
    if (widget.onExpansionChanged != null) {
      widget.onExpansionChanged!(_isExpanded);
    }
  }

  Widget _buildHeader(BuildContext context, Widget? child) {
    return Container(
      color: widget.backgroundColor,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          KqInkWell(
            backgroundColor: widget.backgroundColor ?? KqThemeColors.bgWhite,
            onTap: () {
              _handleTap();
            },
            child: Container(
              padding: EdgeInsets.only(
                  left: (widget.headerPaddingHorizontal ?? 16.r) +
                      widget.headerExtraPaddingLeft,
                  right: widget.headerPaddingHorizontal ?? 16.r,
                  top: widget.headerPaddingVertical ?? 14.r,
                  bottom: widget.headerPaddingVertical ?? 14.r),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  //左侧箭头
                  Visibility(
                      visible: widget.arrowPosition == ArrowPosition.left,
                      child: Image.asset(
                        (_isExpanded
                            ? (widget.iconDownArrow ??
                                Images.commonIcYizhankai16Grey)
                            : (widget.iconUpArrow ??
                                Images.commonIcYishouqi16Grey)),
                        width: 16.r,
                        height: 16.r,
                        color: widget.arrowIconColor,
                        package: widget.iconDownArrow == null
                            ? KqGlobal.packageName
                            : null,
                      )),
                  // 头部和箭头的距离
                  Visibility(
                      visible: widget.arrowPosition == ArrowPosition.left,
                      child: SizedBox(
                        width: widget.arrowHeaderSpacing,
                        height: 1,
                      )),
                  //头部内容
                  Expanded(child: widget.headerWidget),
                  // 头部和箭头的距离
                  Visibility(
                      visible: widget.arrowPosition == ArrowPosition.right,
                      child: SizedBox(
                        width: widget.arrowHeaderSpacing,
                        height: 1,
                      )),
                  //右侧箭头
                  Visibility(
                      visible: widget.arrowPosition == ArrowPosition.right,
                      child: Image.asset(
                        (_isExpanded
                            ? (widget.iconDownArrow ??
                                Images.commonIcJiantouBottom16)
                            : (widget.iconUpArrow ??
                                Images.commonIcJiantouTop16)),
                        width: 16.r,
                        height: 16.r,
                        color: widget.arrowIconColor,
                        package: widget.iconDownArrow == null
                            ? KqGlobal.packageName
                            : null,
                      ))
                ],
              ),
            ),
          ),

          /// 分割线
          Visibility(
              visible: !widget.hideDivider,
              child: Container(
                padding: EdgeInsets.only(
                    left: widget.headerExtraPaddingLeft > 0
                        ? 16.r + widget.headerExtraPaddingLeft
                        : 0),
                child: KqDivider(
                  color: widget.dividerColor,
                ),
              )),

          /// 可展开收起项
          ClipRect(
            child: Align(
              heightFactor: _heightFactor.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final bool closed = !_isExpanded && _controller.isDismissed;
    return AnimatedBuilder(
      animation: _controller.view,
      builder: _buildHeader,
      child: closed
          ? null
          : Container(
              padding: EdgeInsets.only(left: widget.childPaddingLeft),
              child: Column(children: widget.childWidgets),
            ),
    );
  }
}

/// 箭头位置
enum ArrowPosition {
  ///左侧
  left,

  ///右侧
  right
}
